﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShenLanCMS.Models;
using System.Web.Security;
using PagedList;

namespace ShenLanCMS.Web.Controllers
{
    public class UserController : Controller
    {
        private EntityContext db = new EntityContext();

        //分页
        int pageSize = 20;

        [IsAdmin]
        public ViewResult Index(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "Index";

            var list = db.Users.Where(n => n.Status != 2).ToPagedList(index, pageSize);
            return View(list);
        }

        //个人中心
        [IsLogon]
        public ActionResult Myinfo(User u)
        {
            var user = Session["users"] as ShenLanCMS.Models.User;
            if (Request.HttpMethod == "GET")
            {
            }
            else
            {
                db.Entry(u).State = EntityState.Modified;
                db.SaveChanges();
            }
            return View(user);
        }

        //管理员列表
        [IsAdmin]
        public ViewResult Adminuser(int? page)
        {
            var index = (page ?? 1) - 1;
            ViewData["actionName"] = "Index";

            var list = db.Users.Where(n => n.Status == 2).ToPagedList(index, pageSize);
            return View(list);
        }

        //删除管理员
        [IsAdmin]
        public ActionResult DelAdminuser(Guid id)
        {
            try
            {
                var user = Session["users"] as ShenLanCMS.Models.User;
                if (user.UserName.ToLower() != "administrator")
                    return Json("管理员只有超级管理员administrator才能删除");
                var u = db.Users.Find(id);
                if (u.UserName.ToLower() == "administrator")
                    return Json("不能删除超级管理员administrator");
                db.Users.Remove(u);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }

        //设置管理员
        [IsAdmin]
        [HttpPost]
        public ActionResult SetAdmin()
        {
            var user = Session["users"] as ShenLanCMS.Models.User;
            if (user.UserName != "administrator")
                return Json("操作失败!只有超级管理员administrator才能进行该操作");
            try
            {
                var mod = Request.QueryString["mod"];
                var id = Guid.Parse(Request.QueryString["id"]);
                var u = db.Users.Find(id);
                db.Entry(u).State = EntityState.Modified;
                //设置为管理员
                if (mod == "addadmin")
                {
                    u.Status = 2;
                }
                //删除管理员身份
                else
                {
                    u.Status = 1;
                }
                db.SaveChanges();
                return Json("操作成功");
            }
            catch { return Json("操作失败"); }
        }

        public ViewResult Details(Guid id)
        {
            User user = db.Users.Find(id);
            return View(user);
        }

        //添加用户
        [IsAdmin]
        public ActionResult Add()
        {
            return View();
        }

        //注册
        [HttpPost]
        [IsAdmin]
        public ActionResult Add(AddUserModel add)
        {
            if (ModelState.IsValid)
            {
                foreach (var us in db.Users)
                {
                    //判断用户名是否已经存在
                    if (us.UserName == add.UserName)
                    {
                        ModelState.AddModelError("UserName", "该用户名已经存在");
                        return View(add);
                    }
                }
                //事务,同步users和userinfoes
                using (var ts = new System.Transactions.TransactionScope())
                {
                    //用户详细信息
                    var userinfo = new UserInfo();
                    userinfo.UserInfoID = Guid.NewGuid();
                    userinfo.Sex = true;
                    db.UserInfoes.Add(userinfo);
                    db.SaveChanges();

                    //用户
                    var user = new ShenLanCMS.Models.User();
                    user.UserID = Guid.NewGuid();
                    user.UserInfoID = userinfo.UserInfoID;
                    user.Email = "";
                    user.LastActivityTime = DateTime.Now;
                    user.Password = add.Password;
                    user.PasswordAnswer = "";
                    user.PasswordQuestion = "";
                    user.RegTime = DateTime.Now;
                    user.Status = 2;
                    user.UserName = add.UserName;
                    db.Users.Add(user);
                    db.SaveChanges();

                    //事务完成
                    ts.Complete();
                }
                return RedirectToAction("Adminuser");
            }

            return View();
        }

        //注册
        public ActionResult Reg()
        {
            return View();
        }

        //注册
        [HttpPost]
        public ActionResult Reg(RegisterModel rm)
        {
            if (ModelState.IsValid)
            {
                foreach (var us in db.Users)
                {
                    //判断用户名是否已经存在
                    if (us.UserName == rm.UserName)
                    {
                        ModelState.AddModelError("UserName", "该用户名已经存在");
                        return View(rm);
                    }
                }
                //事务,同步users和userinfoes
                using (var ts = new System.Transactions.TransactionScope())
                {
                    //用户详细信息
                    var userinfo = new UserInfo();
                    userinfo.UserInfoID = Guid.NewGuid();
                    userinfo.Sex = true;
                    db.UserInfoes.Add(userinfo);
                    db.SaveChanges();

                    //用户
                    var user = new ShenLanCMS.Models.User();
                    user.UserID = Guid.NewGuid();
                    user.UserInfoID = userinfo.UserInfoID;
                    user.Email = rm.Email;
                    user.LastActivityTime = DateTime.Now;
                    user.Password = rm.Password;
                    user.PasswordAnswer = rm.PasswordAnswer;
                    user.PasswordQuestion = rm.PasswordQuestion;
                    user.RegTime = DateTime.Now; 
                    user.UserName = rm.UserName;                  
                    if (user.UserName.ToLower() == "administrator")
                        user.Status = 2;
                    else
                        user.Status = 1;                   
                    db.Users.Add(user);
                    db.SaveChanges();

                    //同步登录
                    Session["users"] = user;

                    //事务完成
                    ts.Complete();
                }
                return Redirect("/");
            }

            return View();
        }

        //修改密码
        [IsLogon]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //修改密码
        [IsLogon]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel cp)
        {
            var user = Session["users"] as ShenLanCMS.Models.User;
            if (user.Password != cp.OldPassword)
            {
                ModelState.AddModelError("OldPassword", "旧密码不正确!");
                return View(cp);
            }
            //修改
            db.Entry(user).State = EntityState.Modified;
            user.Password = cp.NewPassword;
            db.SaveChanges();
            ModelState.AddModelError("", "修改成功!");
            return View();
        }

        //登录
        public ActionResult Logon()
        {
            return View();
        }

        //登录
        [HttpPost]
        public ActionResult Logon(LogOnModel lo)
        {
            var user = db.Users.SingleOrDefault(n => n.UserName == lo.UserName && n.Password == lo.Password);
            if (user == null)
            {
                ModelState.AddModelError("", "登录失败,用户名或密码错误!");
                return View(lo);
            }
            Session["users"] = user;

            //登录成功则跳回登录前的页面
            var from = Request.QueryString["from"];
            if (!string.IsNullOrEmpty(from))
                return Redirect(from);

            return RedirectToAction("Index", "Home");
        }

        //注销
        public ActionResult Logoff()
        {
            Session["users"] = null;
            return Redirect("/");
        }

        [IsAdmin]
        public ActionResult Edit(Guid id)
        {
            User user = db.Users.Find(id);
            return View(user);
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Edit(User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(user);
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Delete(Guid id)
        {
            try
            {
                var logon = Session["users"] as ShenLanCMS.Models.User;

                User user = db.Users.Find(id);
                //管理员不给删除
                if (user.Status == 2)
                {
                    if (user.UserName.ToLower() != "administrator")
                        return Json("您不是超级管理员administrator,不能删除管理员");
                }
                db.Users.Remove(user);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }



        //#region AcccountController

        //[HttpPost]
        //public ActionResult LogOn(LogOnModel model, string returnUrl)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (Membership.ValidateUser(model.UserName, model.Password))
        //        {
        //            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
        //            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
        //                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
        //            {
        //                return Redirect(returnUrl);
        //            }
        //            else
        //            {
        //                return RedirectToAction("Index", "Home");
        //            }
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "提供的用户名或密码不正确。");
        //        }
        //    }

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    return View(model);
        //}

        ////
        //// GET: /Account/LogOff

        //public ActionResult LogOff()
        //{
        //    FormsAuthentication.SignOut();

        //    return RedirectToAction("Index", "Home");
        //}

        ////
        //// GET: /Account/Register

        //public ActionResult Register()
        //{
        //    return View();
        //}

        ////
        //// POST: /Account/Register

        //[HttpPost]
        //public ActionResult Register(RegisterModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        // 尝试注册用户
        //        MembershipCreateStatus createStatus;
        //        Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
        //            return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    return View(model);
        //}

        //[Authorize]
        //public ActionResult ChangePassword()
        //{
        //    return View();
        //}

        //[Authorize]
        //[HttpPost]
        //public ActionResult ChangePassword(ChangePasswordModel model)
        //{
        //    if (ModelState.IsValid)
        //    {

        //        // 在某些出错情况下，ChangePassword 将引发异常，
        //        // 而不是返回 false。
        //        bool changePasswordSucceeded;
        //        try
        //        {
        //            MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
        //            changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
        //        }
        //        catch (Exception)
        //        {
        //            changePasswordSucceeded = false;
        //        }

        //        if (changePasswordSucceeded)
        //        {
        //            return RedirectToAction("ChangePasswordSuccess");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "当前密码不正确或新密码无效。");
        //        }
        //    }

        //    // 如果我们进行到这一步时某个地方出错，则重新显示表单
        //    return View(model);
        //}

        ////
        //// GET: /Account/ChangePasswordSuccess

        //public ActionResult ChangePasswordSuccess()
        //{
        //    return View();
        //}

        //private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        //{
        //    // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
        //    // 状态代码的完整列表。
        //    switch (createStatus)
        //    {
        //        case MembershipCreateStatus.DuplicateUserName:
        //            return "用户名已存在。请输入不同的用户名。";

        //        case MembershipCreateStatus.DuplicateEmail:
        //            return "该电子邮件地址的用户名已存在。请输入不同的电子邮件地址。";

        //        case MembershipCreateStatus.InvalidPassword:
        //            return "提供的密码无效。请输入有效的密码值。";

        //        case MembershipCreateStatus.InvalidEmail:
        //            return "提供的电子邮件地址无效。请检查该值并重试。";

        //        case MembershipCreateStatus.InvalidAnswer:
        //            return "提供的密码取回答案无效。请检查该值并重试。";

        //        case MembershipCreateStatus.InvalidQuestion:
        //            return "提供的密码取回问题无效。请检查该值并重试。";

        //        case MembershipCreateStatus.InvalidUserName:
        //            return "提供的用户名无效。请检查该值并重试。";

        //        case MembershipCreateStatus.ProviderError:
        //            return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

        //        case MembershipCreateStatus.UserRejected:
        //            return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

        //        default:
        //            return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
        //    }
        //}

        //#endregion

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}